package com.lagou.edu.service;

import com.lagou.edu.utils.ConnectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.SQLException;

/**
 * 事务管理器：手动实现事务管理，单例实现
 *
 * @author: liuhongfei
 * @create: 2021/11/25 19:30
 */
@Component("transactionManager")
public class TransactionManager {
    @Autowired
    private ConnectionUtils connectionUtils;

    //
    // private TransactionManager() {
    // }
    //
    // private static TransactionManager transactionManager = new TransactionManager();
    //
    // public static TransactionManager getInstance() {
    //     return transactionManager;
    // }

    /**
     * 开启事务
     *
     * @throws SQLException
     */
    public void begin() throws SQLException {
        connectionUtils.getCurrentThreadConnection().setAutoCommit(false);
    }

    /**
     * 提交事务
     *
     * @throws SQLException
     */
    public void commit() throws SQLException {
        connectionUtils.getCurrentThreadConnection().commit();
    }

    /**
     * 回滚事务
     *
     * @throws SQLException
     */
    public void rollback() throws SQLException {
        connectionUtils.getCurrentThreadConnection().rollback();
    }
}
